package it.amicosmanettone.finance.stocky;

import it.amicosmanettone.finance.stocky.mysql.UserFunctions;

import org.json.JSONObject;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;

public class MailActivity extends SherlockActivity {

	String nameOfActivity;
	Button buttonSend;

	String textErrorSend;
	String textError;

	private static String KEY_SUCCESS = "success";

	boolean NETWORK;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mail);

		this.NETWORK = isNetworkAvailable();
		if (NETWORK == false) {

			errorConnection();

		}

		setupActionBar();

		Intent i = getIntent();
		this.nameOfActivity = i.getStringExtra("nameOfActivity");

		String titleBug = getText(R.string.titleMailBug).toString();
		String titleAdvice = getText(R.string.titleMailAdvice).toString();
		String textWelcomeString = getText(R.string.textWelcome).toString();

		TextView textWelcome = (TextView) findViewById(R.id.textWelcome);
		textWelcome.setText(textWelcomeString);

		this.buttonSend = (Button) findViewById(R.id.buttonSend);
		final EditText textMessage = (EditText) findViewById(R.id.textMessage);

		if (this.nameOfActivity.equals("reportBug")) {

			setTitle(titleBug);
			getSupportActionBar().setIcon(R.drawable.ic_action_bug);
			this.buttonSend.setText(titleBug);

		} else if (this.nameOfActivity.equals("reportAdvice")) {

			setTitle(titleAdvice);
			getSupportActionBar().setIcon(R.drawable.ic_action_advice);
			this.buttonSend.setText(titleAdvice);

		}

		final ProgressDialog mProgressDialog = new ProgressDialog(this);

		this.buttonSend.setOnClickListener(new View.OnClickListener() {

			public void onClick(final View view) {

				NETWORK = isNetworkAvailable();
				if (NETWORK == false) {

					errorConnection();

				}

				final EditText textMessageEdit = textMessage;

				String textDialogSendMail = getText(R.string.textDialogSendMail)
						.toString();

				mProgressDialog.setMessage(textDialogSendMail);

				new Thread(new Runnable() {

					JSONObject json = null;

					public void run() {

						int erroreMessaggio = 0;

						String MESSAGGIO = "";

						if (textMessageEdit.getText() != null) {
							MESSAGGIO = textMessageEdit.getText().toString();
						}
						if (MESSAGGIO.isEmpty()) {
							erroreMessaggio = 1;
						}

						// No error
						if (erroreMessaggio == 0) {
							runOnUiThread(new Runnable() {
								@Override
								public void run() {

									mProgressDialog.show();

								}
							});

							UserFunctions userFunction = new UserFunctions();

							if (nameOfActivity.equals("reportBug")) {
								Log.e("ACTIVITY", "PROVO BUG");
								this.json = userFunction.sendMailBug(MESSAGGIO);
								runOnUiThread(new Runnable() {
									@Override
									public void run() {
										mProgressDialog.dismiss();
										okBox();
									}
								});

							} else if (nameOfActivity.equals("reportAdvice")) {
								Log.e("ACTIVITY", "PROVO ADVICE");
								this.json = userFunction
										.sendMailAdvice(MESSAGGIO);
								runOnUiThread(new Runnable() {
									@Override
									public void run() {
										mProgressDialog.dismiss();
										okBox();
									}
								});

							}

							/*
							 * try { Log.e("ACTIVITY", "STO PER CONTROLLARE");
							 * if (json.getString(KEY_SUCCESS) != null) { String
							 * res = json .getString(KEY_SUCCESS); if
							 * (Integer.parseInt(res) == 1) {
							 * mProgressDialog.dismiss(); runOnUiThread(new
							 * Runnable() {
							 * 
							 * @Override public void run() { okBox(); } });
							 * 
							 * } else {
							 * 
							 * mProgressDialog.dismiss(); runOnUiThread(new
							 * Runnable() {
							 * 
							 * @Override public void run() {
							 * errorBox("ERROR_SEND"); } });
							 * 
							 * } } } catch (JSONException e) {
							 * e.printStackTrace(); }
							 */

						} else {
							runOnUiThread(new Runnable() {
								@Override
								public void run() {
									errorBox("ERROR_WRITE");
								}
							});
						}// End if no error
					}// End run
				}).start();// End thread

			}
		});

	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private void setupActionBar() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:

			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	public void okBox() {
		
		String text = null;
		
		if (this.nameOfActivity.equals("reportBug")) {
			
			text = getText(R.string.textOkBoxBug).toString();
			
		}if (this.nameOfActivity.equals("reportAdvice")) {
			
			text = getText(R.string.textOkBoxAdvice).toString();
			
		}

		
		final Intent mainIntent = new Intent(this, MainActivity.class);		
		mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK );
		

		new AlertDialog.Builder(this)
				.setMessage(text)
				.setCancelable(false)
				.setNeutralButton(android.R.string.ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {

								startActivity(mainIntent);

							}
						}).show();

	}

	public void errorBox(final String ACTION) {

		if (ACTION.equals("ERROR_SEND")) {

			this.textErrorSend = getText(R.string.textDialogSendMailErrorSend)
					.toString();

		} else if (ACTION.equals("ERROR_WRITE")) {

			this.textErrorSend = getText(R.string.textDialogSendMailErrorText)
					.toString();

		}

		final Intent mainIntent = new Intent(this, MainActivity.class);

		new AlertDialog.Builder(this)
				.setMessage(this.textErrorSend)
				.setCancelable(false)
				.setNeutralButton(android.R.string.ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {

								if (ACTION.equals("ERROR_SEND")) {

									startActivity(mainIntent);

								}

							}
						}).show();

	}

	private void errorConnection() {

		this.textError = getText(R.string.addStockNoConnection).toString();

		String OKButton = getText(R.string.buttonErrorBoxOK).toString();

		new AlertDialog.Builder(this)
				.setMessage(textError)
				.setCancelable(false)
				.setNeutralButton(OKButton,
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int whichButton) {

								finish();

							}
						}).show();

	}// End errorConnection

	private boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager
				.getActiveNetworkInfo();
		return activeNetworkInfo != null;
	}// End isNetworkAvailable

}
